package com.yzg.simple.netty.officialchat.server;

import com.yzg.simple.netty.http.NettyHttpInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author misterWei
 * @mailbox mynameisweiyan@gmail.com
 *
 * Netty 官方版写法,基于私聊,群发 实现思路;
 */
public class NettyOfficialTcpServer {

    //指定端口号
    protected  final   int port;
    //服务器端两个NioEventLoopGroup;
    private  EventLoopGroup bossGroup;
    private  EventLoopGroup workerGroup;

    public NettyOfficialTcpServer(int port){
       this.port = port;
    }

    public void run()throws Exception{
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap()
                         .group(bossGroup,workerGroup)
                           //保持链接数量
                           .option(ChannelOption.SO_BACKLOG,128)
                            //保持活动状态
                             .childOption(ChannelOption.SO_KEEPALIVE,true)
                               .channel(NioServerSocketChannel.class)
                                .childHandler(new NettyOfficialTcpServerInitializer());

            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();

        }
    }

    public static void main(String[] args) throws Exception {
        new NettyOfficialTcpServer(6666).run();
    }
}
